/**
 * 全局配置
 */
var HOST="/protocol";
//var HOST="http://118.24.13.142:8080/protocol";
/**
 * 关ajax缓存
 */
$(function(){
    $.ajaxSetup ({
        cache: false //关闭AJAX缓存
    });
});

var config={
    token: getCookie("token"),
    username: getSessionStorage("username"),
    // role: getCookie("role"),
};

isOnline();
//webCheckLogin();
// getRole();
loadUserInfo();
getAuthorizationState();

function isOnline(role) {
    var res=true;
    if (role==""||role==null||role==undefined) {
        getRole();
    }else{
        $.ajax({
            url:HOST.concat("/isonline?token="+getCookie("token"))+"&username="+getSessionStorage("username"),
            type:"GET",
            dataType:"json",
            async:false,
            success:function (data) {
                // console.log(data);
                if (data.meta.state=="success"){
                    if (data.meta.message=="online"){
                        //用户在线情况下
                        checkRole(role);//防止角色越权
                    } else{
                        //用户离线
                        alert("您已离线,请重新登录");
                        sessionStorage.clear();
                        window.location.href = "login.html";
                        res=false;
                        //return false;
                    }
                } else{
                    //用户离线
                    alert("您已离线,请重新登录");
                    sessionStorage.clear();
                    window.location.href = "login.html";
                    res=false;
                    // return false;
                }

            },
            error:function () {
                alert("您已离线,请重新登录");
                sessionStorage.clear();
                window.location.href = "login.html";
                res=false;
                // return false;
            }
        });

        return res;
    }
}

function getRole(){
    //获取用户角色
    var res;
    $.ajax({
        url: HOST.concat("/userInfo?token=") + getCookie("token"),
        async:false,
        type: 'GET',
        success: function(datas){
            //console.log(datas);
            if (datas.meta.state=="success"){
                checkLogin(datas);
                var username=datas.data.username;
                var role=datas.data.role;
                var createTime=datas.data.createTime;
                setSessionStorage("username",username);
                setSessionStorage("role",role);
                setSessionStorage("createTime",createTime);
                res=role;
            }else {
                window.location.href = "login.html";
            }

        },
        error: function(){
            console.log("error");
        },
        dataType: "json",
    });
    return res;
}



//获取url信息
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if(r != null) {
        return unescape(r[2]);
        //return decodeURI(r[2]); //解决中文乱码问题
    }
}

/**
 * 通用js代码
 */

function setCookie(cname,cvalue,exdays)
{
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

/**
 * 获取cookie
 */
function getCookie(cname)
{
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++)
    {
        var c = $.trim(ca[i]);
        if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}

/**
 * 删除全部cookie
 */
function clearCookie(){
    var keys=document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (var i = keys.length; i--;){
            document.cookie=keys[i]+'=0;expires=' + new Date(0).toUTCString()
        }
    }
}


/**
 * 从session中回去元素
 * */
function getSessionStorage(key){
    // console.log("sess:"+JSON.stringify(window.sessionStorage));
    var val = window.sessionStorage.getItem(key);
    return val==null?"无取值":val;
}

/**
 * 从session设置元素
 * */
function setSessionStorage(key,val){
    window.sessionStorage.setItem(key, val);
}

function logout(){
	$.ajax({
		url: HOST.concat("/logout?token=") + config.token,
		type: 'POST',
		success: function(){
			location.href = "login.html";
		},
		error: function(){
            console.log("登出错误！");
        },
        dataType: "json",
	});
}


/**
 * 加载用户名、角色方法
 */
function loadUserInfo(){

    $(".username").html(getSessionStorage("username"));
    $("#createTime").html(getSessionStorage("createTime"));

    if(getSessionStorage("role")==="admin"){
        $(".role").html("管理员");
    }
    else if(getSessionStorage("role")==="operator"){
        $(".role").html("操作员");
    }
    else if(getSessionStorage("role")==="auditor"){
        $(".role").html("审计员");
    }
    else if(getSessionStorage("role")==="sysAuditor"){
        $(".role").html("系统审计员");
    }

    //点击登录按钮
    $("#logout").click(function(){
        //webCheckLogin();
        var role=getSessionStorage('role');
        isOnline(role);
        sessionStorage.clear();
        clearCookie();
        logout();
    });
}

/**
 * 后端判断是否登录或过期
 */
function checkLogin(res){
	if("notlogin"==res["meta"]["message"]){
		window.location.href = "login.html";
	}
}
/**
 * 页面加载前判断登录或过期
 */
function webCheckLogin() {
    var pathname = window.location.pathname;
    if(pathname=="/login.html"){
        console.log("");
    }else {
        var token = getCookie("token");
        if(token!=""){
            $.ajax({
                url: HOST.concat("/checkLogin?token=") + token,
                type: 'GET',
                success: function(datas){
                    checkLogin(datas);
                },
                error: function(){
                    console.log("check错误！");
                    alert("您已离线");
                    window.location.href = "login.html";
                },
                dataType: "json",
            });
        }else {
            window.location.href = "login.html";
        }
    }

}

function checkAuthorizationState() {
    $.ajax({
        url:HOST.concat("/checkauthorizationstate?token=")+config.token,
        type:"GET",
        data:{
            "username":config.username
        },
        async:false,
        dataType:"json",
        success:function (res) {
            if(res.meta.state=="success"){
                var data=res.data;
                config["permissionState"]=data.permissionState;
                sessionStorage.setItem("permissionState",data.permissionState);
                if(data.permissionState!=2){
                    window.location.href = "askauthorization.html";
                }
            }
        },
        error: function(){
            console.log("check authorization error！");
        }

    });
}

function getAuthorizationState() {
    $.ajax({
        url:HOST.concat("/checkauthorizationstate?token=")+config.token,
        type:"GET",
        data:{
            "username":config.username
        },
        async:false,
        dataType:"json",
        success:function (res) {
            if(res.meta.state=="success"){
                var data=res.data;
                config["permissionState"]=data.permissionState;
                sessionStorage.setItem("permissionState",data.permissionState);
            }
        },
        error: function(){
            console.log("get authorization error！");
        }
    });

}

function checkFirstLogin() {
    $.ajax({
        url: HOST.concat("/checkFirst?token=") + config.token,
        type: 'GET',
        data:{
            "username":config.username
        },
        success: function(res){
            if("firstlogin"==res["meta"]["message"]){
                window.location.href = "pswChange.html";
            }

        },
        error: function(){
            console.log("check error！");
        },
        dataType: "json",
    });
}

function produceWarning(urlPathname) {
    $.ajax({
        url:HOST.concat("/producewarning?token="+config.token),
        type:"POST",
        dataType:"json",
        data:{
            "username":config.username,
            "urlPathname":urlPathname
        },
        async:false
    });
}

/**
 * 进页面判断角色
 */
function checkRole(role) {
    checkFirstLogin();
    checkAuthorizationState();
    config.role=getRole();
    if(config.role!=role){
        var urlPathname = window.location.pathname;
        produceWarning(urlPathname);
        // window.alert("信息;越权访问");
         window.location.href="accessDenied.html";

    }
}



//特殊字符：  "[`~!@#$^%&*()=|{}':;',\\[\\].<>~！@#￥……&*（）——|{}‘’【】‘；：”“'。，、？]"

/**
 * 二合一
 * */

function IsNotSpecialCharAndNotEmpty(s) {
    if(s.trim()==""){
        return false;
    }
    var str="[`~!@#$^%&*=|{}':;',\\[\\].<>~！@#￥……&*（）——|{}‘’【】‘；：”“'。，、？]";

    for (var j = 0; j < s.length; j++) {
        if(str.indexOf(s.substr(j, 1))!=-1){
            //含有特殊字符
            console.log("特殊字符:"+s.substr(j,1));
            return false;
        }
    }

    return true;
}

/**
 * 备注判断是否有特殊字符
 * */

function IsSpecialChar(s,obj) {
    //括号不能算特殊字符()  备注 逗号不算特殊
    var str = "[`~!@#$^%&*=|{}':;'\\[\\]<>~！@#￥……&*（）——|{}‘’【】‘；：”“'？]";
    for (var j = 0; j < s.length; j++) {
        if (str.indexOf(s.substr(j, 1)) != -1) {
            //alert(obj+"中请勿填写特殊字符!");
            // console.log("特殊字符:"+s.substr(j, 1));
            return false;
        }
    }
    return true;
}

/**
 * 判断字段名称不能为空;
 * */

function  IsFieldNameNotEmpty(str) {
    if(str.trim()==""){
        //alert("字段名称不能为空!");
        return false;
    }
    return true;
}


/**
 * 比较两个时间大小
 * */
function compareFromAndTo(from,to) {
    var fromTime = from.toString().split("-")
    var toTime = to.toString().split("-");
    console.log(fromTime);
    console.log(toTime);
    if((fromTime[0]>toTime[0])||
        (fromTime[0]==toTime[1] && fromTime[1]>toTime[1])||
        (fromTime[0]==toTime[1] && fromTime[1]==toTime[1]&&fromTime[2]>toTime[2])){
        return false;
    }else {
        return true;
    }
}

/**
 * 用户尚未授权和密码修改页面的退出
 * */
$("#myLogout").click(function(){
    sessionStorage.clear();
    clearCookie();
    logout();
});

/**
 * 根据传入对象的属性来显示按钮
 * */
function myBtnClick(obj){
    //刚开始的时候obj身上肯定是没有isChoosen这个属性的
    //则$(obj).attr("isChoosen")获取指定属性的返回值就是false，执行else里面的代码
    if($(obj).attr("isChoosen")){
        $(obj).css("background-color", "rgb(255,255,255)");
        $(obj).css("color", "rgb(0,0,0)");
        $(obj).removeAttr("isChoosen");
    }else{
        $(obj).css("background-color", "rgb(224,224,224)");
        $(obj).css("color", "rgb(48,148,222)");
        $(obj).attr("isChoosen","true");
    }
}

